package com.labofjet.system.generator.task.impl;

import com.labofjet.system.dto.SysCodeDto;
import com.labofjet.system.generator.context.TaskContext;
import com.labofjet.system.generator.dto.FieldDto;
import com.labofjet.system.generator.dto.TableDto;
import com.labofjet.system.generator.enums.ETaskDefine;
import com.labofjet.system.generator.mapper.SysTaskMapper;
import com.labofjet.system.generator.task.Task;
import com.labofjet.system.generator.util.GeneratorUtils;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 初始化任务,加载各种必备数据,比如表信息,字段信息
 */
@Component("DBInitTask")
public class DBInitTask implements Task {

	@Resource
	SysTaskMapper sysTaskMapper;

	@Override
	public boolean doTask(TaskContext c) {
		// table和package网页设置
		String tableName = c.get(ETaskDefine.TABLE.getCode());
		String packageName = c.get(ETaskDefine.PACKAGE_NAME.getCode());

		// 设置classname和JavaName,url
		c.put(ETaskDefine.CLASSNAME_SHORT.getCode(), GeneratorUtils.underlineNameToJavaNameAndUpCaseFirstLetter(tableName));
		c.put(ETaskDefine.VARIABLE.getCode(), GeneratorUtils.underlineNameToJavaName(tableName));
		SysCodeDto codeDto = c.get(ETaskDefine.RESULT.getCode());
		codeDto.setClassName(c.get(ETaskDefine.CLASSNAME_SHORT.getCode()));
		codeDto.setJavaName(c.get(ETaskDefine.VARIABLE.getCode()));
		int index = tableName.indexOf("_");
		String result = tableName.substring(index + 1, tableName.length()).replaceAll("_", "").toLowerCase();
		codeDto.setUrl(result);

		// 加载Field信息
		Map<String, Object> params = new HashMap<>();
		params.put(ETaskDefine.TABLE.getCode(), tableName);
		List<FieldDto> fieldInfos = sysTaskMapper.getFieldInfo(params);
		for (FieldDto fieldInfo : fieldInfos) {
			fieldInfo.setJavaName(GeneratorUtils.underlineNameToJavaName(fieldInfo.getField()));
		}
		c.put(ETaskDefine.FIELDS_INFO.getCode(), fieldInfos);

		// 加载table信息
		params.clear();
		params.put(ETaskDefine.TABLE.getCode(), tableName);
		TableDto tableInfo = sysTaskMapper.getTableInfo(params);
		c.put(ETaskDefine.TABLE_INFO.getCode(), tableInfo);

		return true;
	}

}
